package dk.lector.datasource;

import android.content.ContentProviderClient;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.util.Log;
import dk.lector.R;
import dk.lector.domain.TSSystemIntent;
import dk.lector.domain.TeamShareMobile;
import dk.lector.domain.entities.User;
import dk.lector.exception.TSMobileException;
import dk.lector.providers.USERContentProvider;

public class UserDBRepository {

	private static final String TAG = UserDBRepository.class.getSimpleName();
	
	
public static User cacheUser(Context context, ContentValues values){ 
	TeamShareMobile core = (TeamShareMobile) context.getApplicationContext();
	if(!core.hasConfig()) return null;
	
	ContentProviderClient client = context.getContentResolver().acquireContentProviderClient(context.getString(R.string.user_authority));
	Log.d(TAG, "Trying to cache userdata");
	User result = null;
	try {
		Cursor c = client.query(USERContentProvider.CONTENT_URI, USERContentProvider.PROJECTION, null, null, null);
		User temp = cursorLoop(c);
		if(temp!=null)
		{
		Log.d(TAG,"Temp null check: " + temp.toString() + " returning excisting entry");
		context.sendBroadcast(new TSSystemIntent(R.string.ACTIONCODE_USER_LOGIN, TAG));
		return temp;
		}
		Uri uri = client.insert(USERContentProvider.CONTENT_URI, values);
		Log.d(TAG, "URI retured from insert: " + uri);
		result = toUserObject(client, uri);
		
	} catch (RemoteException e) {
		throw new TSMobileException(e, UserDBRepository.class, "cacheUser", "Error during create");
	}catch (Exception e) {
	throw new TSMobileException(e, UserDBRepository.class, "cacheUser", "General exception...Shieeeeeeeeeet niggah");
}
	finally{client.release();}
	
	Log.d(TAG, "Looks to be working! Result: " + result.toString());
	if(result!=null)context.sendBroadcast(new TSSystemIntent(R.string.ACTIONCODE_USER_LOGIN, TAG));
	
	return result;
}

public static Cursor readUserCursor(Context context)
{
	ContentProviderClient client = context.getContentResolver().acquireContentProviderClient(context.getString(R.string.user_authority));
	Cursor c = null;
	try {
		c = client.query(USERContentProvider.CONTENT_URI, USERContentProvider.PROJECTION, null, null, null);
	} catch (RemoteException e) {
		throw new TSMobileException(e, UserDBRepository.class, "readUserCursor", "Error during create");
	}
	finally{client.release();}
	
	return c;
}






public static User readUser(Context context)
{
	ContentProviderClient client = context.getContentResolver().acquireContentProviderClient(context.getString(R.string.user_authority));
	User result = new User();
	try {
		Cursor c = client.query(USERContentProvider.CONTENT_URI, USERContentProvider.PROJECTION, null, null, null);
		result = cursorLoop(c);
	} 
	catch (RemoteException e) 
	{
		throw new TSMobileException(e, UserDBRepository.class, "readUser", "Error during create");
	}
	finally{client.release();}
	if(result != null)
	Log.d(TAG, "Looks to be working! Result: " + result.toString());
	return result;
}

public static boolean deleteUser(Context context)
{
	ContentProviderClient client = context.getContentResolver().acquireContentProviderClient(context.getString(R.string.user_authority));
	int deletedUser = 0;
	boolean deletedDocuments = false;
	boolean result = false;
	try {
		deletedUser = client.delete(USERContentProvider.CONTENT_URI, null, null);
		deletedDocuments = DocDBRepository.deleteAllDocuments(context);
	} catch (RemoteException e) {
		throw new TSMobileException(e, UserDBRepository.class, "deleteUser", "Error during create");
	}
	finally{client.release();}
	result = (deletedUser>0&&deletedDocuments)?true:false;
	Log.d(TAG, "Delete user result: " + result);
	if(result)context.sendBroadcast(new TSSystemIntent(R.string.ACTIONCODE_USER_LOGOUT, TAG));
	return result;
}

public static void updateUserActivity(Context context, long timestamp,int userId) 
{
	
//	ContentProviderClient client = context.getContentResolver().acquireContentProviderClient(context.getString(R.string.user_authority));
//	int updated = 0;
//	ContentValues updateValue = new ContentValues();
//	updateValue.put(USERContentProvider.TIMESTAMP_ACTIVITY, timestamp);
//	
//	try {
//		updated = client.update(USERContentProvider.TIMESTAMP_ACTIVITY_FIELD_CONTENT_URI, updateValue , USERContentProvider._ID + " == ", new String[]{String.valueOf(userId)});
//	} catch (RemoteException e) {
//		throw new TSMobileException(e, UserDBRepository.class, "updateUserActivity", "Error during update");
//	}finally{client.release();}
//	Log.d(TAG, "user activity timestamp was updated : " + String.valueOf((updated>0)));
}

private static User toUserObject(ContentProviderClient currentClient, Uri uri) throws RemoteException
{
	Cursor c = currentClient.query(uri, USERContentProvider.PROJECTION, null, null, null);
	return (c!=null)?cursorLoop(c):null;

	
}
private static User cursorLoop(Cursor cursor)
{
	User result = new User();
	cursor.moveToFirst();
	Log.d(TAG, "User cursor count: " + cursor.getCount());
	if(cursor.getCount()>0){
	
		result.setId(cursor.getInt(0));
		result.setUsername(cursor.getString(1));
		result.setPassword(cursor.getString(2));
		result.setUsernamePlain(cursor.getString(3));
		result.setEmail(cursor.getString(4));
		result.setFullName(cursor.getString(5));
		result.setTimestamp(cursor.getLong(6));
		result.setTimestampActivity(cursor.getLong(7));

	}
	else return null;
	cursor.close();
	Log.d(TAG, "After cursorLoop: " + result.toString());
	return result;
}



}
	
	
	

